package com.example.test_1_21.mqserver.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

//表示一个交换机
public class Exchange {
    //此处使用name来作为交换机的唯一身份标识
    private String name;
    //交换机类型，DIRECT，FANOUT，TOPIC
    private ExchangeType type=ExchangeType.DIRECT;
    //该交换机是否需要持久化，true表示需要持久化；false表示不必持久化
    private boolean durable=false;
    //当前交换机，没有人使用了，就会自动删除
    private boolean autoDelete=false;
    //arguments表示的是创建交换机时指定的一些额外的参数选项
    private Map<String,Object> arguments=new HashMap<>();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public ExchangeType getType() {
        return type;
    }

    public void setType(ExchangeType exchangeType) {
        this.type = exchangeType;
    }

    public boolean isDurable() {
        return durable;
    }

    public void setDurable(boolean durable) {
        this.durable = durable;
    }

    public boolean isAutoDelete() {
        return autoDelete;
    }

    public void setAutoDelete(boolean autoDelete) {
        this.autoDelete = autoDelete;
    }

    //用于和数据库交互使用的arguments
    public String getArguments() {
        //把当前的arguments参数，从Map转换成String（JSON）
        ObjectMapper objectMapper=new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(arguments);
        }catch (JsonProcessingException e){
            e.printStackTrace();
        }
        return "{}";
    }

    public void setArguments(String argumentJson) {
        ObjectMapper objectMapper=new ObjectMapper();
        try {
            this.arguments=objectMapper.readValue(argumentJson, new TypeReference<HashMap<String,Object>>() {});
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    //针对arguments的测试中，提供一组getter和setter，用来方便获取和设置键值对
    public Object getArguments(String key){
        return arguments.get(key);
    }

    public void setArguments(String key, Object value) {
        arguments.put(key,value);
    }

    public void setArguments(Map<String,Object> arguments){
        this.arguments=arguments;
    }
}
